package com.snowruin.distributed.lock.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.springframework.util.ResourceUtils;

/**
 * 文件 工具类
 * @author zxm
 * @version 1.0.0
 * @date 2019-03-05 10:43:21
 * @url https://www.snowruin.com
 *
 */
public class FileUtils {
	
	private FileUtils() {}
	
	/**
	 * 读取文件
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static String  readFileToString (String fileName)  {
		FileInputStream fileInputStream = null;
		try {
			File file = ResourceUtils.getFile("classpath:"+fileName);
			fileInputStream = new FileInputStream(file);
			FileChannel channel = fileInputStream.getChannel();
			
			ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
			
			channel.read(byteBuffer);
			
			byteBuffer.flip();
			
			StringBuilder  sb = new StringBuilder();
			
			while(byteBuffer.remaining() > 0) {
				byte b = byteBuffer.get();
				sb.append((char)b);	
			}
			
			fileInputStream.close();
			return sb.toString();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(fileInputStream != null) {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}
